<?php
namespace app\user\controller;

use think\facade\Request;
use app\common\traits\JWT;
use app\login\controller\WxMiniprogramLogin as wxminiprogramLogin;

class Login extends Base
{
    use JWT;
    
    private $wxminiprogramCtl;
    
    // 终端对应，作为可扩展的登录选项
    const TERMINAL_NAME = [
        0 => 'wxminiprogram', // 微信小程序
    ];
    
    public function __construct() {
        parent::__construct();
    }
    
    public function index()
    {
        return '访问错误';
        exit;
    }
    
    // 设置全局用户ID，除此处外，不应在别处修改全局用户ID
    private function setCurUserId($jwt){
        $GLOBALS['current_user_id'] = $this->getUserIdFromJWT($jwt);
    }
    
    /**
     * 钩子函数绑定的检测jwt是否有效的函数,不对外开放
     * @param string $jwt
     * @param string $return_type json|bool 主要用于返回true，使应用执行下去
     * */
    public function checkJwtValid($jwt=NULL, $return_type='json') {
        
        if($jwt != NULL){
            $flag = $this->checkJWT($jwt);
            
            if($flag){
                // 设置全局用户ID
                $this->setCurUserId($jwt);
                if($return_type == 'json'){
                    $this->coutHandler->outputJson(lang('valid JWT'), 200);
                }else{
                    return true;
                }
            }else{
                $this->coutHandler->outputJson(lang('unvalid JWT'), 250);
            }
        }else{
            $this->coutHandler->outputJson(lang('not login'), 250);
        }
        
    }
    
    // 对外登录接口，根据终端参数选择不同登录方式
    public function loginAction() {
        
        $code = $this->request->param('code');
        $terminal = $this->request->param('terminal');
        $userInfo = $this->request->param('userInfo');
        
        // 禁止GET方式提交
        $this->commonCtl->notAllowGetMethod();

        // 根据终端参数选择登录方式
        switch ($terminal){
            case 0 :
                // 小程序
                $this->wxminiprogramCtl = new wxminiprogramLogin();
                $loginRes = $this->wxminiprogramCtl->wxminiprogramLogin($code, $userInfo);
                if($loginRes['status'] == 200){
                    // 封装JWT
                    $jwt = $this->generateJWT($loginRes['data']['userId']);
                    
                    $this->coutHandler->outputJson($loginRes['txt'], 200, array('userId' => $loginRes['data']['userId'], 'jwt' => $jwt));
                }else{
                    $this->coutHandler->outputResJson($loginRes);
                }
                break;
            default:
                $this->coutHandler->outputJson(lang('wrong terminal ID'), 250);
                break;
        }
    }
    
    // 对外接口，判断jwt是否有效，有效则设置全局用户ID
    public function checkJwtValidAction() {
        
        $jwt = $this->request->param('jwt', NULL);
        
        $this->checkJwtValid($jwt);
    }
}